/**
 * @Author LoliServer
 */
package moe.loliserver.utils;

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import moe.loliserver.LanguagesMap;
import moe.loliserver.LoliServerStart;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;

public class UpdateCheckerUtil {
    public final String CHECK_API = "http://nat.loliidc.cn:33644/job/LoliServer1.16/lastSuccessfulBuild/api/json";

    public UpdateCheckerUtil() {
        try {

            JsonElement inputJson = new JsonParser().parse(new InputStreamReader(getInputStream(CHECK_API)));
            String JENKINS_NUMBER = inputJson.getAsJsonObject().get("number").toString();
            String LATEST_VERSION = "1.16.5-" + JENKINS_NUMBER;
            String LATEST_FILENAME = "LoliServer-" + LATEST_VERSION + "-server" + ".jar";
            String LOLISERVER_VERSION = LoliServerStart.getVersion();
            String DOWNLOADFILE_API = "http://nat.loliidc.cn:33644/job/LoliServer1.16/lastSuccessfulBuild/artifact/projects/LoliServer/build/libs/" + LATEST_FILENAME;

            // LoliServer Start
            if (LOLISERVER_VERSION.isEmpty() || JENKINS_NUMBER.isEmpty()) {
                System.out.println(LanguagesMap.i18nGet("loli.updatenull"));
            }
            if (LOLISERVER_VERSION.equals(LATEST_VERSION)) {
                System.out.println(LanguagesMap.i18nGet("loli.noupdate"));
            } else {
                File file = new File(LATEST_FILENAME);
                System.out.println(String.format(LanguagesMap.i18nGet("loli.outdate"), LATEST_VERSION));
                downloadFile(DOWNLOADFILE_API, file);
                System.out.println(String.format(LanguagesMap.i18nGet("loli.update"), LATEST_FILENAME));
                System.out.println(LanguagesMap.i18nGet("loli.editbash"));
                System.out.println(LanguagesMap.i18nGet("loli.editbash1"));
                System.exit(0);
            }
            // LoliServer End
        } catch (IOException e) {
            System.out.println(String.format(LanguagesMap.i18nGet("launch.lib_failure_download"), e));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static URLConnection sendRequest(String URL){
        URLConnection urlConnection = null;
        try {
            urlConnection = new URL(URL).openConnection();
            urlConnection.setRequestProperty("Accept", "*/*");
            urlConnection.setRequestProperty("Connection", "Close");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return urlConnection;
    }

    public static InputStream getInputStream(String URL) throws IOException {
        return sendRequest(URL).getInputStream();
    }

    public static void downloadFile(String downloadUrl, File saveFile) throws IOException {
        URL url = new URL(downloadUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(8000);
        connection.setRequestMethod("GET");

        System.out.println(String.format(LanguagesMap.i18nGet("launch.lib_downloading"), saveFile.getName(), getSize(connection.getContentLengthLong())));

        ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());
        FileOutputStream fos = new FileOutputStream(saveFile);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        rbc.close();
        fos.close();

        connection.disconnect();
    }

    public static String getSize(long size) {
        if (size >= 1048576L) { return size / 1048576.0F + " MB"; }
        if (size >= 1024) { return size / 1024.0F + " KB"; }
        return size + " B";
    }

    public static long getSizeOfDirectory(File path) throws IOException {
        return Files.walk(path.toPath()).parallel().filter(p -> !p.toFile().isDirectory()).count();
    }
}
